package cn.com.b2office.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import cn.com.b2office.dao.CategoryDao;
import cn.com.b2office.domain.Category;
import cn.com.b2office.service.CategoryService;
import edu.emory.mathcs.backport.java.util.Collections;

public class CategoryServiceImpl implements CategoryService {

	private CategoryDao categoryDao = null;

	public void setCategoryDao(CategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	/** 按照类别层次级联列出 */
	public Map<Category, List<Category>> listCascadeCategories() {
		List<Category> list = categoryDao.listCascadeCategories();
		Comparator<Category> comparator = new Comparator<Category>() {
			public int compare(Category c1, Category c2) {
				return c2.getSortwt() - c1.getSortwt();
			}

		};
		Map<Category, List<Category>> map = new TreeMap(comparator);
		// 按照大类排序
		for (int i = 0; i < list.size(); i++) {
			Category category = list.get(i);
			if (category.getItem_clsno().trim().length() == 2) {
				List<Category> childs = new ArrayList<Category>();
				for (int j = i + 1; j < list.size(); j++) {
					Category childCategory = list.get(j);
					if (childCategory.getItem_clsno().trim().length() == 4) {
						childs.add(childCategory);
						i = j;
					} else {
						i = j - 1;
						Collections.sort(childs, comparator);
						map.put(category, childs);
						break;
					}
				}

			}
		}
		return map;

	}

	public List<Category> findDirectChilds(String categoryId) {
		return categoryDao.findDirectChilds(categoryId);
	}

	public Category getCategory(String categoryId) {
		return categoryDao.getCategory(categoryId);
	}

	public List<Category> findAncestries(String categoryId) {
		return categoryDao.listAncestries(categoryId);
	}

	public List<Category> findTopLevelCategories() {
		return categoryDao.findTopLevelCategories();
	}
}
